package com.ruoyi.module.controller;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.module.domain.ExamPaper;
import com.ruoyi.module.domain.ExamQuestion;
import com.ruoyi.module.service.IExamPaperService;
import com.ruoyi.module.service.IExamQuestionService;

/**
 * 试卷Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/module/exam/paper")
public class ExamPaperController extends BaseController
{
    @Autowired
    private IExamPaperService examPaperService;

    @Autowired
    private IExamQuestionService examQuestionService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询试卷列表
     */
    @PreAuthorize("@ss.hasPermi('module:exam:paper:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExamPaper examPaper)
    {
        startPage();
        List<ExamPaper> list = examPaperService.selectExamPaperList(examPaper);
        return getDataTable(list);
    }

    /**
     * 根据ID查询试卷详情
     */
    @PreAuthorize("@ss.hasPermi('module:exam:paper:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ExamPaper examPaper = examPaperService.selectExamPaperById(id);
        if (examPaper != null)
        {
            // 查询关联的试题列表
            List<ExamQuestion> questionList = examQuestionService.selectExamQuestionListByPaperId(id);
            examPaper.setQuestionList(questionList);
        }
        return success(examPaper);
    }

    /**
     * 新增试卷
     */
    @PreAuthorize("@ss.hasPermi('module:exam:paper:add')")
    @Log(title = "试卷管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamPaper examPaper)
    {
        examPaper.setCreateBy(getUsername());
        return toAjax(examPaperService.insertExamPaper(examPaper));
    }

    /**
     * 修改试卷
     */
    @PreAuthorize("@ss.hasPermi('module:exam:paper:edit')")
    @Log(title = "试卷管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamPaper examPaper)
    {
        examPaper.setUpdateBy(getUsername());
        return toAjax(examPaperService.updateExamPaper(examPaper));
    }

    /**
     * 删除试卷
     */
    @PreAuthorize("@ss.hasPermi('module:exam:paper:remove')")
    @Log(title = "试卷管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(examPaperService.deleteExamPaperByIds(ids));
    }

    /**
     * 导入试卷JSON文件
     * JSON格式：
     * {
     *   "version": {
     *     "id": 68,
     *     "versionName": "小升初分类词汇",
     *     "period": "小学"
     *   },
     *   "rawData": {
     *     "0": [
     *       {
     *         "opType": "0",
     *         "opIndex": 1,
     *         "opList": ["n.地形，地貌", "n. 化学；化学物质", "极限自行车运动", "试试这些", "不认识"],
     *         "opId": 141319,
     *         "opSeparate": "chem.is.try",
     *         "opTitle": "chemistry"
     *       }
     *     ]
     *   }
     * }
     */
    @PreAuthorize("@ss.hasPermi('module:exam:paper:add')")
    @Log(title = "试卷导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importExamFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "language", required = false) String language,
            @RequestParam(value = "languageCategory", required = false) String languageCategory)
    {
        try
        {
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty())
            {
                return error("文件名不能为空");
            }
            
            if (!fileName.toLowerCase().endsWith(".json"))
            {
                return error("只支持JSON格式文件");
            }
            
            // 读取JSON内容
            String jsonContent = new String(file.getBytes(), StandardCharsets.UTF_8);
            Map<String, Object> jsonMap = objectMapper.readValue(jsonContent, new TypeReference<Map<String, Object>>() {});
            
            // 解析版本信息
            @SuppressWarnings("unchecked")
            Map<String, Object> versionMap = (Map<String, Object>) jsonMap.get("version");
            if (versionMap == null)
            {
                return error("JSON文件中缺少version字段");
            }
            
            // 创建试卷对象
            ExamPaper examPaper = new ExamPaper();
            if (versionMap.get("id") != null)
            {
                examPaper.setVersionId(Long.valueOf(versionMap.get("id").toString()));
            }
            examPaper.setVersionName(getStringValue(versionMap, "versionName"));
            examPaper.setPeriod(getStringValue(versionMap, "period"));
            examPaper.setLanguage(language);
            examPaper.setLanguageCategory(languageCategory);
            examPaper.setStatus("0");
            examPaper.setCreateBy(getUsername());
            
            // 解析试题数据
            @SuppressWarnings("unchecked")
            Map<String, Object> rawDataMap = (Map<String, Object>) jsonMap.get("rawData");
            if (rawDataMap == null)
            {
                return error("JSON文件中缺少rawData字段");
            }
            
            List<ExamQuestion> questionList = new ArrayList<>();
            int sortOrder = 0;
            
            // 遍历rawData中的所有分类（如"0", "1"等）
            for (Map.Entry<String, Object> entry : rawDataMap.entrySet())
            {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> questionArray = (List<Map<String, Object>>) entry.getValue();
                
                if (questionArray != null)
                {
                    for (Map<String, Object> questionMap : questionArray)
                    {
                        ExamQuestion question = new ExamQuestion();
                        question.setOpType(getStringValue(questionMap, "opType"));
                        question.setOpIndex(getIntegerValue(questionMap, "opIndex"));
                        question.setOpId(getLongValue(questionMap, "opId"));
                        question.setOpSeparate(getStringValue(questionMap, "opSeparate"));
                        question.setOpTitle(getStringValue(questionMap, "opTitle"));
                        
                        // 处理选项列表
                        Object opListObj = questionMap.get("opList");
                        if (opListObj != null)
                        {
                            if (opListObj instanceof List)
                            {
                                @SuppressWarnings("unchecked")
                                List<String> opList = (List<String>) opListObj;
                                // 将选项列表转换为JSON字符串存储
                                question.setOpList(objectMapper.writeValueAsString(opList));
                                question.setOpListArray(opList);
                            }
                            else
                            {
                                question.setOpList(opListObj.toString());
                            }
                        }
                        
                        question.setSortOrder(sortOrder++);
                        question.setStatus("0");
                        question.setCreateBy(getUsername());
                        questionList.add(question);
                    }
                }
            }
            
            if (questionList.isEmpty())
            {
                return error("JSON文件中没有找到有效的试题数据");
            }
            
            // 保存试卷
            examPaper.setTotalQuestions(questionList.size());
            int paperResult = examPaperService.insertExamPaper(examPaper);
            if (paperResult <= 0)
            {
                return error("保存试卷信息失败");
            }
            
            // 设置试题的试卷ID
            for (ExamQuestion question : questionList)
            {
                question.setPaperId(examPaper.getId());
            }
            
            // 批量插入试题
            int questionCount = examQuestionService.batchInsertExamQuestion(questionList);
            
            return success(String.format("试卷导入成功！共导入 %d 道试题", questionCount));
            
        }
        catch (Exception e)
        {
            logger.error("导入试卷失败", e);
            return error("导入试卷失败：" + e.getMessage());
        }
    }

    /**
     * 租户前台：随机获取试题
     * 随机返回40道题，如果不够40就返回试题总量的一半
     */
    @GetMapping("/{paperId}/random")
    public AjaxResult getRandomQuestions(@PathVariable("paperId") Long paperId)
    {
        List<ExamQuestion> questionList = examQuestionService.selectRandomExamQuestions(paperId);
        
        // 将opList从JSON字符串转换为数组
        for (ExamQuestion question : questionList)
        {
            if (StringUtils.isNotEmpty(question.getOpList()))
            {
                try
                {
                    @SuppressWarnings("unchecked")
                    List<String> opList = objectMapper.readValue(question.getOpList(), List.class);
                    question.setOpListArray(opList);
                }
                catch (Exception e)
                {
                    logger.warn("解析选项列表失败: {}", question.getOpList(), e);
                }
            }
        }
        
        return success(questionList);
    }

    /**
     * 从Map中获取字符串值
     */
    private String getStringValue(Map<String, Object> map, String key)
    {
        Object value = map.get(key);
        if (value != null)
        {
            return value.toString();
        }
        return null;
    }

    /**
     * 从Map中获取整数值
     */
    private Integer getIntegerValue(Map<String, Object> map, String key)
    {
        Object value = map.get(key);
        if (value != null)
        {
            if (value instanceof Integer)
            {
                return (Integer) value;
            }
            try
            {
                return Integer.valueOf(value.toString());
            }
            catch (NumberFormatException e)
            {
                return null;
            }
        }
        return null;
    }

    /**
     * 从Map中获取长整数值
     */
    private Long getLongValue(Map<String, Object> map, String key)
    {
        Object value = map.get(key);
        if (value != null)
        {
            if (value instanceof Long)
            {
                return (Long) value;
            }
            if (value instanceof Integer)
            {
                return ((Integer) value).longValue();
            }
            try
            {
                return Long.valueOf(value.toString());
            }
            catch (NumberFormatException e)
            {
                return null;
            }
        }
        return null;
    }
}

